﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EscPrinterVfpV1d0.Entity
{
    /// <summary>
    /// TcpClientWithTimeout 用来设置一个带连接超时功能的类
    /// 使用者可以设置毫秒级的等待超时时间 (1000=1second)
    /// </summary>
    public class TcpClientWithTimeoutV1d0
    {
        private static bool IsConnectionSuccessful = false;
        private static Exception socketexception;
        private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
        public static TcpClient TryConnect(string serverip, int serverport, int timeoutMiliSecond)
        {
            TimeoutObject.Reset();
            socketexception = null;
            TcpClient tcpclient = new TcpClient();
            try
            {
                //设定发数据的超时时间
                tcpclient.SendTimeout = 1000;
                tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient);
                //等待信号timeoutMiliSecond事件若干秒，
                if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
                {
                    if (IsConnectionSuccessful)
                    {
                        return tcpclient;
                    }
                    else
                    {
                        throw socketexception;
                    }
                }
                else
                {
                    //在指定时间内没有等到信号，则关闭tpclient，发出超时异常
                    IsConnectionSuccessful = false;
                    tcpclient.Close();
                    tcpclient = null;
                    throw new TimeoutException("TimeOut Exception");
                }
            }
            catch (Exception ex)
            {
                //SimpleLoger.Instance.Error(ex);
            }
            return tcpclient;
        }
        /// <summary>
        /// 异步连接的回调函数
        /// </summary>
        /// <param name="asyncresult"></param>
        private static void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnectionSuccessful = false;
                TcpClient tcpClient = asyncresult.AsyncState as TcpClient;
                if (tcpClient.Client != null)
                {
                    tcpClient.EndConnect(asyncresult);
                    IsConnectionSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                IsConnectionSuccessful = false;
                socketexception = ex;
            }
            finally
            {
                //线程继续运行
                TimeoutObject.Set();
            }
        }
    }
}
